<template>
  <div class="mobile-app">
    <!-- 顶部导航栏 -->
    <el-header class="mobile-header">
      <div class="header-content">
        <!-- 左侧下拉菜单 -->
        <el-dropdown @command="handleMenuCommand" class="nav-dropdown">
          <el-button type="primary" :icon="Menu" circle />
          <template #dropdown>
            <el-dropdown-menu>
              <!-- 固定的首页和工作日志 -->
              <el-dropdown-item command="/" :class="{ active: $route.path === '/' }">
                <el-icon><House /></el-icon>
                <span>客户经理工作台</span>
              </el-dropdown-item>
              <el-dropdown-item command="/work-log" :class="{ active: $route.path === '/work-log' }">
                <el-icon><Calendar /></el-icon>
                <span>工作日志</span>
              </el-dropdown-item>
              
              <!-- 动态服务项目 -->
              <el-dropdown-item 
                v-for="service in dynamicServices" 
                :key="service.id"
                :command="service.path" 
                :class="{ active: $route.path === service.path }"
              >
                <el-icon><component :is="service.icon" /></el-icon>
                <span>{{ service.name }}</span>
              </el-dropdown-item>
              
              <!-- 分隔线 -->
              <el-divider style="margin: 8px 0;" />
              
              <!-- 固定的客户管理 -->
              <el-dropdown-item command="/client-management" :class="{ active: $route.path === '/client-management' }">
                <el-icon><Management /></el-icon>
                <span>客户管理</span>
              </el-dropdown-item>
              
              <!-- 固定的任务提醒 -->
              <el-dropdown-item command="/task-reminder" :class="{ active: $route.path === '/task-reminder' }">
                <el-icon><Bell /></el-icon>
                <span>任务提醒</span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>

        <!-- 中间页面标题 -->
        <div class="page-title">
          {{ currentPageTitle }}
        </div>

        <!-- 右侧退出登录 -->
        <el-button
          type="danger"
          :icon="SwitchButton"
          circle
          @click="handleLogout"
          class="logout-btn"
        />
      </div>
    </el-header>

    <!-- 主要内容区域 -->
    <el-main class="mobile-main" :style="{ paddingBottom: $route.meta?.showTabbar ? '70px' : '20px' }">
      <div class="mobile-container">
        <router-view :key="$route.fullPath" />
      </div>
    </el-main>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, onMounted, markRaw } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  House,
  Calendar,
  Menu,
  SwitchButton,
  UserFilled,
  Medal,
  Star,
  Document,
  Connection,
  Bell,
  User,
  TrendCharts,
  Phone,
  Avatar,
  Management
} from "@element-plus/icons-vue"
import { trpc } from '@/utils/trpc'

const router = useRouter()
const route = useRoute()

// 动态服务项目
const dynamicServices = ref<any[]>([])

// 服务项目图标映射（与 Home.vue 保持一致）
const serviceIconMap: Record<string, any> = {
  '客户拜访': markRaw(User),
  '诚信五化建设': markRaw(TrendCharts),
  '客户评价': markRaw(Star),
  '满意度调查': markRaw(Phone),
  '四员协同': markRaw(Avatar),
  '工作日志': markRaw(Document),
}

// 获取服务项目的图标
function getServiceIcon(serviceName: string) {
  return serviceIconMap[serviceName] || markRaw(Document)
}

// 生成服务项目的路由路径
function getServicePath(serviceName: string) {
  const pathMap: Record<string, string> = {
    '客户拜访': '/client-visit',
    '诚信五化建设': '/integrity-building',
    '客户评价': '/client-evaluation',
    '满意度调查': '/satisfaction-survey',
    '四员协同': '/team-collaboration',
    '工作日志': '/work-log'
  }
  return pathMap[serviceName] || `/service/${encodeURIComponent(serviceName)}`
}

// 计算当前页面标题
const currentPageTitle = computed(() => {
  return route.meta?.title || '客户经理拜访系统'
})

// 加载动态服务项目
const loadDynamicServices = async () => {
  try {
    const serviceList = await trpc.service.list.query({ pageSize: 100 })
    if (serviceList?.success) {
      const services = serviceList.data.data || serviceList.data || []
      
      // 构建动态服务项目（排除工作日志，因为它是固定的）
      dynamicServices.value = services
        .filter((service: any) => service.serviceName !== '工作日志')
        .map((service: any) => ({
          id: service.id,
          name: service.serviceName,
          icon: getServiceIcon(service.serviceName),
          path: getServicePath(service.serviceName)
        }))
    }
  } catch (error) {
    console.error('加载服务项目失败:', error)
  }
}

// 处理菜单命令
const handleMenuCommand = (command: string) => {
  if (command !== route.path) {
    router.push(command)
  }
}

// 处理退出登录
const handleLogout = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要退出登录吗？',
      '退出确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    // 清除登录状态
    localStorage.removeItem('manager_token')
    localStorage.removeItem('manager_name')

    ElMessage.success('已退出登录')

    // 跳转到登录页
    router.push('/login')
  } catch {
    // 用户取消退出
  }
}

// 初始化
onMounted(() => {
  loadDynamicServices()
})
</script>

<style scoped>
.mobile-app {
  height: 100vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background-color: #f8f9fa;
}

/* 顶部导航栏样式 */
.mobile-header {
  flex-shrink: 0;
  height: 60px !important;
  line-height: normal !important;
  padding: 0 !important;
  background: linear-gradient(135deg, #409eff 0%, #1890ff 100%);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  height: 100%;
}

.nav-dropdown {
  flex-shrink: 0;
}

.page-title {
  flex: 1;
  text-align: center;
  font-size: 1.1rem;
  font-weight: 600;
  color: white;
  margin: 0 16px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.logout-btn {
  flex-shrink: 0;
}

/* 下拉菜单样式 */
:deep(.nav-dropdown .el-button) {
  background: rgba(255, 255, 255, 0.2) !important;
  border: 1px solid rgba(255, 255, 255, 0.3) !important;
  color: white !important;
}

:deep(.nav-dropdown .el-button:hover) {
  background: rgba(255, 255, 255, 0.3) !important;
  border-color: rgba(255, 255, 255, 0.4) !important;
}

:deep(.logout-btn.el-button--danger) {
  background: rgba(245, 108, 108, 0.9) !important;
  border: 1px solid rgba(245, 108, 108, 0.6) !important;
  color: white !important;
}

:deep(.logout-btn.el-button--danger:hover) {
  background: rgba(245, 108, 108, 1) !important;
  border-color: rgba(245, 108, 108, 0.8) !important;
}

/* 下拉菜单项样式 */
:deep(.el-dropdown-menu) {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  padding: 8px 0;
  min-width: 200px;
}

:deep(.el-dropdown-menu__item) {
  padding: 12px 16px;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #606266;
  transition: all 0.3s;
}

:deep(.el-dropdown-menu__item:hover) {
  background-color: #f0f9ff;
  color: #409eff;
}

:deep(.el-dropdown-menu__item.active) {
  background-color: #e6f7ff;
  color: #409eff;
  font-weight: 500;
}

:deep(.el-dropdown-menu__item .el-icon) {
  font-size: 16px;
  width: 16px;
  height: 16px;
}

/* 主内容区域样式 */
.mobile-main {
  flex: 1;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  padding: 0 0;
  background-color: #f8f9fa;
}

.mobile-container {
  padding: 0 16px;
}

/* 底部导航栏样式 */
.mobile-tabbar {
  flex-shrink: 0;
  background: white;
  border-top: 1px solid #e4e7ed;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
}

.tabbar-menu {
  background: white !important;
  border: none !important;
  height: 60px;
  margin: 0;
}

.tabbar-item {
  flex: 1;
  height: 60px !important;
  line-height: normal !important;
  padding: 0 !important;
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  border-bottom: none !important;
}

.tabbar-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.tabbar-content .el-icon {
  font-size: 20px;
  color: #909399;
  transition: color 0.3s;
}

.tabbar-content span {
  font-size: 12px;
  color: #909399;
  transition: color 0.3s;
}

:deep(.tabbar-menu .el-menu-item) {
  border-bottom: none !important;
  color: #909399 !important;
  background: transparent !important;
}

:deep(.tabbar-menu .el-menu-item.is-active) {
  background: transparent !important;
}

:deep(.tabbar-menu .el-menu-item.is-active .tabbar-content .el-icon) {
  color: #409eff !important;
}

:deep(.tabbar-menu .el-menu-item.is-active .tabbar-content span) {
  color: #409eff !important;
  font-weight: 500;
}

:deep(.tabbar-menu .el-menu-item:hover) {
  background: #f5f7fa !important;
}

:deep(.tabbar-menu .el-menu-item:hover .tabbar-content .el-icon) {
  color: #409eff;
}

:deep(.tabbar-menu .el-menu-item:hover .tabbar-content span) {
  color: #409eff;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .header-content {
    padding: 0 0;
  }

  .page-title {
    font-size: 1rem;
    margin: 0 0;
  }

  .mobile-container {
    padding: 0 0;
  }
}

/* 安全区域适配 */
.mobile-header {
  padding-top: env(safe-area-inset-top);
}

/* 深色模式适配 */
@media (prefers-color-scheme: dark) {
  .mobile-app {
    background-color: #1a1a1a;
  }

  .mobile-main {
    background-color: #1a1a1a;
  }

  :deep(.el-dropdown-menu) {
    background-color: #2d2d2d;
    border-color: #404040;
  }

  :deep(.el-dropdown-menu__item) {
    color: #e5e5e5;
  }

  :deep(.el-dropdown-menu__item:hover) {
    background-color: #404040;
    color: #409eff;
  }

  :deep(.el-dropdown-menu__item.active) {
    background-color: #1e3a8a;
    color: #60a5fa;
  }
}
</style>
